package com.ruoyi.project.system.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.smsInfo.domain.SmsInfo;
import com.ruoyi.project.channel.smsInfo.service.ISmsInfoService;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.pay.mail.IMailService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/*")
public class LoginController extends BaseController {
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISmsInfoService smsInfoService;
    @Autowired
    private IMailService mailService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        mmap.put("title", payConfig.getTitle().replace("新", ""));
        mmap.put("title2", payConfig.getTitle());

//        String agent = request.getHeader("user-agent");
//        boolean isPc = true;
//        if (agent.toLowerCase().contains("android") || agent.toLowerCase().contains("webos") || agent.toLowerCase().contains("iphone") || agent.toLowerCase().contains("blackberry")) {
//            isPc = false;
//        }
//        if(!isPc){
//            return "loginMobile";
//        }
        return "login";
//        return "loginNew";
    }

    @GetMapping("/userLogout")
    @ResponseBody
    public AjaxResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return AjaxResult.success("success","success");
    }

    @GetMapping("/title")
    @ResponseBody
    public AjaxResult getTitle() {
        return AjaxResult.success("success",payConfig.getTitle());
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe, String phoneCode) {
        long startTime=System.currentTimeMillis();
        System.out.println("登录开始时间："+startTime);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);

        Subject subject = SecurityUtils.getSubject();
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(date);
        String ip = ServletUtils.getRequest().getRemoteHost();
        String address = "XX XX";

        try {
            address = AddressUtils.getRealAddressByIP(ip);
        } catch (Exception e) {
        }

        User user = userService.selectUserByLoginName(token.getUsername());
//        if (user.getPhonenumber() != null && !"".equals(user.getPhonenumber().trim())
//        ) {
//            // 有手机号 但是没输入验证码
//           boolean b = smsInfoService.validateCode(user.getPhonenumber(),phoneCode.trim());
//            if (!b) {
//                return error("手机验证码出错！");
//            }
//        }

        if (user.getSecretKey() != null && !"".equals(user.getSecretKey().trim())
        ) {
            // 有手机号 但是没输入验证码
            boolean success = GoogleAuthenticatorUtils.verify(user.getSecretKey(), phoneCode.trim());
            if (!success) {
                String content = "您的账号:" + user.getLoginName() + "于" + time + "在" + address + "输错谷歌验证码,ip地址:" + ip;
                if (user.getPhonenumber() != null && !"".equals(user.getPhonenumber().trim())) {
//                    SMSUtil.sendSms(content, user.getPhonenumber().trim());
                }
                if (user.getEmail() != null && !"".equals(user.getEmail().trim())) {
//                    mailService.sendSimpleMail(user.getEmail().trim(),"支付管理台",content);
                }
                long endTime=System.currentTimeMillis();
                System.out.println("登录结束时间："+endTime+";"+(endTime-startTime));
                return error("谷歌验证码出错！");
            }
        }

        try {

            subject.login(token);
            String content = "您的账号:" + user.getLoginName() + "于" + time + "在" + address + "登录,ip地址:" + ip;
            if (user.getPhonenumber() != null && !"".equals(user.getPhonenumber().trim())) {
//                SMSUtil.sendSms(content, user.getPhonenumber().trim());
            }
            if (user.getEmail() != null && !"".equals(user.getEmail().trim())) {
//                mailService.sendSimpleMail(user.getEmail().trim(),"支付管理台",content);
            }
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            String content = "您的账号:" + token.getUsername() + "于" + time + "在" + address + "输错密码,ip地址:" + ip;
            if (user.getPhonenumber() != null && !"".equals(user.getPhonenumber().trim())) {
//                SMSUtil.sendSms(content, user.getPhonenumber().trim());
            }
            if (user.getEmail() != null && !"".equals(user.getEmail().trim())) {
//                mailService.sendSimpleMail(user.getEmail().trim(),"支付管理台",content);
            }
            return error(msg);
        }
    }
    @PostMapping("/loginH5")
    @ResponseBody
    public AjaxResult ajaxLoginH5(@RequestBody HashMap<String,String> info) {
        long startTime=System.currentTimeMillis();
        System.out.println("登录开始时间："+startTime);
        UsernamePasswordToken token = new UsernamePasswordToken(info.get("userName"), info.get("password"), Boolean.valueOf(info.get("rememberMe")));

        Subject subject = SecurityUtils.getSubject();
//        User user = userService.selectUserByLoginName(token.getUsername());
        try {
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }


    /**
     * 当前操作人员手机发送短信
     *
     * @return
     */
    @PostMapping("/sendPwdCode")
    @ResponseBody
    public AjaxResult sendCode() {
//        User user = userService.selectUserById(ShiroUtils.getSysUser().getUserId());
//        String phoneNum = user.getPhonenumber();
//        if(phoneNum == null || phoneNum.trim().equals("")){
//            return AjaxResult.error("未绑定手机号，无权操作");
//        }
//        smsInfoService.doSendCode(user);
//        String phone_ = phoneNum.substring(0, 3) + "********" + phoneNum.substring(7, phoneNum.length());
//        return AjaxResult.success("成功", phone_);

        User user = userService.selectUserById(ShiroUtils.getSysUser().getUserId());
        String email = user.getEmail();
        if(email == null || email.trim().equals("")){
            return AjaxResult.error("未绑定email号，无权操作");
        }
        smsInfoService.doSendCode(user);
        String [] tmp =  email.split("@");
        String phone_ = email.substring(0, 3) + "********" + tmp[1];
        return AjaxResult.success("成功", phone_);
    }

    /**
     * 是否需要发短信验证
     *
     * @param username 用户名
     * @return
     */
    @PostMapping("/needCode")
    @ResponseBody
    public AjaxResult needCode(String username) {
        User user = userService.selectUserByLoginName(username);
        if (user == null) {
            return AjaxResult.error("用户名输入错误");
        }
//        if (user.getPhonenumber() == null || user.getPhonenumber().trim().equals("")) {
//            return AjaxResult.success("成功", "noNeed");
//        }
        if (user.getSecretKey() == null || user.getSecretKey().trim().equals("")) {
            return AjaxResult.success("成功", "noNeed");
        }
//        smsInfoService.doSendCode(user);
//        String phoneNum = user.getPhonenumber();
//        String phone_ = phoneNum.substring(0, 3) + "********" + phoneNum.substring(7, phoneNum.length());
        return AjaxResult.success("成功", "");
    }

    /**
     * 当前操作人员手机发送短信
     *
     * @return
     */
    @PostMapping("/sendPhoneCode")
    @ResponseBody
    public AjaxResult sendCode(@RequestBody HashMap<String,String> info) {
//        User user = userService.selectUserById(ShiroUtils.getSysUser().getUserId());
//        String phoneNum = user.getPhonenumber();
//        if(phoneNum == null || phoneNum.trim().equals("")){
//            return AjaxResult.error("未绑定手机号，无权操作");
//        }
//        smsInfoService.doSendCode(user);
//        String phone_ = phoneNum.substring(0, 3) + "********" + phoneNum.substring(7, phoneNum.length());
//        return AjaxResult.success("成功", phone_);
        return AjaxResult.success("成功", info.get(""));
    }


    @GetMapping("/unauth")
    public String unauth() {
        return "/error/unauth";
    }

}
